package edu.upb.acs.jobsmaps.activity.add;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import com.google.android.gms.maps.GoogleMap;
import edu.upb.acs.jobsmaps.R;
import edu.upb.acs.jobsmaps.database.task.AddCompanyTask;
import edu.upb.acs.jobsmaps.entity.Company;
import edu.upb.acs.jobsmaps.voice.VoiceUtils;

import java.util.ArrayList;
import java.util.List;

public class AddCompanyActivityVoice extends FragmentActivity {
	private static final String TAG = AddCompanyActivityVoice.class.getName();

    final Context context = this;
    private Button addButton;
    private PopupWindow pw;
    private GoogleMap map;

    //voice variables
    private int flag;
    private EditText editBox;
    private Spinner spinner;

    private Button btnSpeakName;
    private Button btnSpeakDescription;
    private Button btnSpeakLatitude;
    private Button btnSpeakLongitude;
	private Button btnSpeakProfile;
	private Button btnSpeakUrl;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addcompanyvoice);

        flag = 0;

		Log.d(TAG, "Initialize activity");

		addListenerOnButton();

        //voice method -> Don't forget to add
        initializeVoiceData();
    }

    private void addListenerOnButton() {
        // components from main.xml
        addButton = (Button) findViewById(R.id.addCompanyButtonAddVoice);

        // add button listener
        addButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                createCompany();

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);
                alertDialogBuilder.setMessage("Company was added with success");
                alertDialogBuilder.setCancelable(false).setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                goToMainActivity();
                            }
                        });
                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();
                // show it
                alertDialog.show();
            }
        });

        Button goBackButton = (Button) findViewById(R.id.addCompanyButtonCancelVoice);
        goBackButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                goToMainActivity();
            }
        });
    }

    private void goToMainActivity() {
        setResult(RESULT_OK);
        finish();
    }

	private void createCompany() {
		final Company company = new Company();

		final EditText nameField = (EditText) findViewById(R.id.addCompanyNameVoice);
		String name = nameField.getText().toString();
		Log.d(TAG, "company name = >" + name + "<");
		company.setName(name);

		String description = ((EditText) findViewById(R.id.addCompanyDescriptionVoice)).getText().toString();
		Log.d(TAG, "company description = >" + description + "<");
		company.setDescription(description);

		String profile = ((Spinner) findViewById(R.id.addCompanyProfileVoice)).getSelectedItem().toString();
		if (!profile.equalsIgnoreCase("any")){
			company.setProfile(profile);
		}
		Log.d(TAG, "company profile = >" + profile + "<");

		Double latitude = Double.valueOf(((EditText) findViewById(R.id.addCompanyLatitudeVoice)).getText().toString());
		company.setLatitude(latitude);
		Log.d(TAG, "company latitude = >" + latitude + "<");

		Double longitude = Double.valueOf(((EditText) findViewById(R.id.addCompanyLongitudeVoice)).getText().toString());
		company.setLongitude(longitude);
		Log.d(TAG, "company longitude = >" + longitude + "<");

		String companyUrl = ((EditText) findViewById(R.id.addCompanyUrlVoice)).getText().toString();
		company.setCompanyUrl(companyUrl);
		Log.d(TAG, "company companyUrl = >" + companyUrl + "<");

		AddCompanyTask addCompanyTask = new AddCompanyTask();
		try {
			Integer persistedCompanyId = addCompanyTask.execute(company).get();
			Log.d(TAG, "New company id = " + persistedCompanyId);
		} catch (Exception e) {
			Log.e(TAG, "Can not persist company", e);
		}
	}
//
//    private void initiatePopupWindow() {
//        try {
//
//            // We need to get the instance of the LayoutInflater, use the
//            // context of this activity
//            LayoutInflater inflater = (LayoutInflater) AddCompanyActivityVoice.this
//                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//            // Inflate the view from a predefined XML layout
//            View layout = inflater.inflate(R.layout.selectcompanylocation,
//                    (ViewGroup) findViewById(R.id.popuplayout));
//
//            // create a 300px width and 470px height PopupWindow
//            pw = new PopupWindow(layout, 300, 470, true);
//
//            // display the popup in the center
//            pw.showAtLocation(layout, Gravity.CENTER, 0, 0);
//            map = ((SupportMapFragment) getSupportFragmentManager()
//                    .findFragmentById(R.id.popupmapview)).getMap();
//            map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
//            map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title(
//                    "Marker"));
//            map.setMyLocationEnabled(true);
//
//            Button buttoncancel = (Button) layout
//                    .findViewById(R.id.selectLocationButtoncancel);
//            buttoncancel.setOnClickListener(new OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    pw.dismiss();
//                }
//
//            });
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }

    //voice methods
    private void initializeVoiceData() {
		final Activity activity = this;

        btnSpeakName = (Button) findViewById(R.id.btnCompanyNameAddVoice);
        btnSpeakName.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                editBox = (EditText) findViewById(R.id.addCompanyNameVoice);
                VoiceUtils.speak(null, null, activity);
                flag = 2;
            }
        });

        btnSpeakDescription = (Button) findViewById(R.id.btnCompanyDescriptionAddVoice);
        btnSpeakDescription.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
				editBox = (EditText) findViewById(R.id.addCompanyDescriptionVoice);
				VoiceUtils.speak(null, null, activity);
                flag = 2;
			}
             });

		//TODO the profile is not filled
		btnSpeakProfile = (Button) findViewById(R.id.btnCompanyProfileAddVoice);
		btnSpeakProfile.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				spinner = (Spinner) findViewById(R.id.addCompanyProfileVoice);
				ArrayAdapter myAdap = (ArrayAdapter) spinner.getAdapter(); //cast to an ArrayAdapter
				int nrElements = myAdap.getCount();

				List<String> valuesSpinner = new ArrayList<>();
				for (int i = 0; i < nrElements; i++) {
					valuesSpinner.add(spinner.getItemAtPosition(i).toString());
				}

				VoiceUtils.speak(null, valuesSpinner, activity);
                flag = 1;
			}
		});

        btnSpeakLongitude = (Button) findViewById(R.id.btnCompanyLongitudeAddVoice);
        btnSpeakLongitude.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                editBox = (EditText) findViewById(R.id.addCompanyLongitudeVoice);
				VoiceUtils.speak(null, null, activity);
                flag = 2;
            }
        });

        btnSpeakLatitude = (Button) findViewById(R.id.btnCompanyLatitudeAddVoice);
        btnSpeakLatitude.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                editBox = (EditText) findViewById(R.id.addCompanyLatitudeVoice);
				VoiceUtils.speak(null, null, activity);
                flag = 2;
            }
        });

		btnSpeakUrl = (Button) findViewById(R.id.btnCompanyUrlAddVoice);
		btnSpeakUrl.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				editBox = (EditText) findViewById(R.id.addCompanyUrlVoice);
				VoiceUtils.speak(null, null, activity);
                flag = 2;
			}
		});

		checkVoiceRecognition();
    }



    public void checkVoiceRecognition() {
        // Check if voice recognition is present
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
                RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() == 0) {
            btnSpeakName.setEnabled(false);
            btnSpeakDescription.setEnabled(false);
            btnSpeakName.setText("Voice recognizer not present");
            btnSpeakDescription.setText("Voice recognizer not present");
            btnSpeakLongitude.setText("Voice recognizer not present");
            btnSpeakLatitude.setText("Voice recognizer not present");
			btnSpeakProfile.setText("Voice recognizer not present");
			btnSpeakUrl.setText("Voice recognizer not present");
            Toast.makeText(this, "Voice recognizer not present",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VoiceUtils.VOICE_RECOGNITION_REQUEST_CODE)

            //If Voice recognition is successful then it returns RESULT_OK
            if (resultCode == RESULT_OK) {

                ArrayList<String> textMatchList = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if (!textMatchList.isEmpty()) {
                    Log.d(TAG, "FLAG IS: " + flag);
                    if (flag == 2){
                        // populate the Matches
                        editBox.setText(textMatchList.get(0));
                    }
                    else if (flag == 1){
                        ArrayAdapter myAdap = (ArrayAdapter) spinner.getAdapter(); //cast to an ArrayAdapter
                        int nrElements = myAdap.getCount();

                        List<String> valuesSpinner = new ArrayList<>();
                        for (int i = 0; i < nrElements; i++) {
                            valuesSpinner.add(spinner.getItemAtPosition(i).toString());
                        }

                        for (int i = 0; i < valuesSpinner.size(); i++) {
                            for (int j = 0; j < textMatchList.size(); j++) {
                                Log.d(TAG, "textMatchList: " + textMatchList.get(j));
                                if (valuesSpinner.get(i).equalsIgnoreCase(textMatchList.get(j))) {
                                    spinner.setSelection(i);
                                }
                            }
                        }
                    }

                }
                //Result code for various error.
            } else if (resultCode == RecognizerIntent.RESULT_AUDIO_ERROR) {
                showToastMessage("Audio Error");
            } else if (resultCode == RecognizerIntent.RESULT_CLIENT_ERROR) {
                showToastMessage("Client Error");
            } else if (resultCode == RecognizerIntent.RESULT_NETWORK_ERROR) {
                showToastMessage("Network Error");
            } else if (resultCode == RecognizerIntent.RESULT_NO_MATCH) {
                showToastMessage("No Match");
            } else if (resultCode == RecognizerIntent.RESULT_SERVER_ERROR) {
                showToastMessage("Server Error");
            }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Helper method to show the toast message
     */
    void showToastMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}
